package com.hfb.mashibing.alip8.system.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {

    public static void main(String[] args) throws IOException {
        System.out.println("1、serverSelector 负责轮询是否有新的连接，服务端检测到有新的连接之后，不在创建一个新的线程");
        System.out.println("而是直接将新连接绑定到 clientSelector 上，这样就不用IO模型中1W个 while 循环在死等");

        Selector serverSelector = Selector.open();

        System.out.println("2、clientSelector 负责轮询连接是否有数据可读");
        Selector clientSelector = Selector.open();

        new Thread(() -> {
            try {
                // 对应IO编程中服务端的启动
                ServerSocketChannel listenerChannel = ServerSocketChannel.open();
                listenerChannel.socket().bind(new InetSocketAddress(3333));
                listenerChannel.configureBlocking(false);
                listenerChannel.register(serverSelector, SelectionKey.OP_ACCEPT);
                while (true) {
                    // 检测是否有新的连接，这里的1是指阻塞时间为1 ms
                    if (serverSelector.select(1) > 0) {
                        Iterator<SelectionKey> keyIterator = serverSelector.selectedKeys().iterator();

                        while (keyIterator.hasNext()) {
                            SelectionKey key = keyIterator.next();
                            if (key.isAcceptable()) {
                                try {
                                    //（1）每来一个新连接，不需要创建一个先吃，而是直接注册到 clientSelector
                                    SocketChannel clientChannel = ((ServerSocketChannel) key
                                        .channel()).accept();
                                    clientChannel.configureBlocking(false);
                                    clientChannel.register(clientSelector, SelectionKey.OP_READ);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } finally {
                                    keyIterator.remove();
                                }
                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        },"ServerThread").start();

        new Thread(() -> {
            while (true) {
                // (2)批量轮询是否有哪些连接有数据可读，这里的1是指阻塞时间为 1ms
                try {
                    if (clientSelector.select(1) > 0) {
                        Iterator<SelectionKey> keyIterator = clientSelector.selectedKeys().iterator();

                        while (keyIterator.hasNext()) {
                            SelectionKey key = keyIterator.next();
                            if (key.isReadable()) {
                                try {
                                    SocketChannel clientChannel = ((ServerSocketChannel) key
                                        .channel()).accept();
                                    // (3)面向 Buffer
                                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                                    clientChannel.read(byteBuffer);
                                    byteBuffer.flip();
                                    System.out.println(Charset.defaultCharset().newDecoder().decode(byteBuffer).toString());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } finally {
                                    keyIterator.remove();
                                    key.interestOps(SelectionKey.OP_READ);
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, "ClientThread").start();

    }

}
